package cn.yunyichina.provider.sb.service.impl;

import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.sb.constant.Constant;
import cn.yunyichina.provider.sb.dao.*;
import cn.yunyichina.provider.sb.entity.*;
import cn.yunyichina.provider.sb.util.Util;
import cn.yunyichina.provider.sb.vo.SbRequest;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alipay.api.response.AlipayCommerceDataSendResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by 15-AK on 2017/9/18.
 */
public class OutlineServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(OutlineServiceImpl.class);

    private MedicalPatientDao medicalPatientDao = SpringContextHandler.getBean("medicalPatientDao");
    private MedicalCheckingDao medicalCheckingDao = SpringContextHandler.getBean("medicalCheckingDao");
    private MedicalCheckingDetailDao medicalCheckingDetailDao = SpringContextHandler.getBean("medicalCheckingDetailDao");
    private MedicalExaminationDao medicalExaminationDao = SpringContextHandler.getBean("medicalExaminationDao");
    private MedicalOperationRecordDao medicalOperationRecordDao = SpringContextHandler.getBean("medicalOperationRecordDao");
    private MedicalOutpatientFeeDao medicalOutpatientFeeDao = SpringContextHandler.getBean("medicalOutpatientFeeDao");
    private MedicalOutpatientFeeDetailDao medicalOutpatientFeeDetailDao = SpringContextHandler.getBean("medicalOutpatientFeeDetailDao");
    private MedicalInhospitalFeeDao medicalInhospitalFeeDao = SpringContextHandler.getBean("medicalInhospitalFeeDao");
    private MedicalInhospitalFeeDetailDao medicalInhospitalFeeDetailDao = SpringContextHandler.getBean("medicalInhospitalFeeDetailDao");
    private MedicalInhospitalReportidsDao medicalInhospitalReportidsDao = SpringContextHandler.getBean("medicalInhospitalReportidsDao");
    private MedicalInhospitalDiagnosisDao medicalInhospitalDiagnosisDao = SpringContextHandler.getBean("medicalInhospitalDiagnosisDao");
    public void uploadOutlineMessage() {
        logger.info("门诊就诊数据概要上传开始");
        MedicalPatient queryMedicalPatient = new MedicalPatient();
        queryMedicalPatient.setOrgCode(Constant.HOSPITAL_CODE);
        queryMedicalPatient.setAllDataUploadCompletedFlag(new Short("0"));
        queryMedicalPatient.setBusinessType(new Short("1"));
        queryMedicalPatient.setAllExaminationDownLoadFlag(new Short("1"));
        queryMedicalPatient.setAllCheckingDwnnLoadFlag(new Short("1"));
        queryMedicalPatient.setAllOperationDownLoadFlag(new Short("1"));
        List<MedicalPatient> medicalPatientList = medicalPatientDao.select(queryMedicalPatient);
        if (CollectionUtils.isNotEmpty(medicalPatientList)) {
            for (MedicalPatient medicalPatient : medicalPatientList) {
                logger.info("mzFeeId={},门诊就诊数据概要待上传就诊人medicalPatient ={}", new Object[]{medicalPatient.getMzFeeId(),JsonUtils.toJsonString(medicalPatient)});

                //已经上传的费用信息
                MedicalOutpatientFee queryHasUploadMedicalOutpatientFee = new MedicalOutpatientFee();
                queryHasUploadMedicalOutpatientFee.setMedicalPatientId(medicalPatient.getId());
                queryHasUploadMedicalOutpatientFee.setUploadFlag(new Short("1"));
                Long hasUploadMedicalOutpatientFeeNum = medicalOutpatientFeeDao.selectCount(queryHasUploadMedicalOutpatientFee);
                //费用信息总条数
                MedicalOutpatientFee queryMedicalOutpatientFee = new MedicalOutpatientFee();
                queryMedicalOutpatientFee.setMedicalPatientId(medicalPatient.getId());
                Long medicalOutpatientFeeNum = medicalOutpatientFeeDao.selectCount(queryMedicalOutpatientFee);
                if (hasUploadMedicalOutpatientFeeNum != medicalOutpatientFeeNum) {
                    continue;
                }
                //已经上传过的费用明细
                MedicalOutpatientFeeDetail queryHasUploadMedicalOutpatientFeeDetail = new MedicalOutpatientFeeDetail();
                queryHasUploadMedicalOutpatientFeeDetail.setMedicalPatientId(medicalPatient.getId());
                queryHasUploadMedicalOutpatientFeeDetail.setUploadFlag(new Short("1"));
                Long hasUploadMedicalOutpatientFeeDetailNum = medicalOutpatientFeeDetailDao.selectCount(queryHasUploadMedicalOutpatientFeeDetail);

                //费用明细总条数
                MedicalOutpatientFeeDetail queryMedicalOutpatientFeeDetail = new MedicalOutpatientFeeDetail();
                queryMedicalOutpatientFeeDetail.setMedicalPatientId(medicalPatient.getId());
                List<MedicalOutpatientFeeDetail> medicalOutpatientFeeDetailList = medicalOutpatientFeeDetailDao.select(queryMedicalOutpatientFeeDetail);
                //已经上传过的费用明细跟费用明细的总条数不相等那么本次完结状态结束
                //费用总条数为0 的情况不存在
                if (CollectionUtils.isEmpty(medicalOutpatientFeeDetailList) || hasUploadMedicalOutpatientFeeDetailNum != medicalOutpatientFeeDetailList.size()) {
                    continue;
                }

                //计算本次门诊流程总的报告条数
                Set<String> medicalCheckingCheckingSet = new HashSet<String>();
                Set<String> medicalExaminationSet = new HashSet<String>();
                Set<String> operationRecordSet = new HashSet<String>();
                    for (MedicalOutpatientFeeDetail medicalOutpatientFeeDetail : medicalOutpatientFeeDetailList) {
                    if (StringUtils.isNotEmpty(medicalOutpatientFeeDetail.getReportId()) && medicalOutpatientFeeDetail.getFeeType() == 9) {
                        medicalCheckingCheckingSet.add(medicalOutpatientFeeDetail.getReportId());
                    }
                    if (StringUtils.isNotEmpty(medicalOutpatientFeeDetail.getReportId()) && medicalOutpatientFeeDetail.getFeeType() == 4) {
                        medicalExaminationSet.add(medicalOutpatientFeeDetail.getReportId());
                    }
                    if (StringUtils.isNotEmpty(medicalOutpatientFeeDetail.getReportId()) && medicalOutpatientFeeDetail.getFeeType() == 10) {
                        operationRecordSet.add(medicalOutpatientFeeDetail.getReportId());
                    }
                }

                Long medicalCheckingDetailNum = 0L;
                if (CollectionUtils.isNotEmpty(medicalCheckingCheckingSet)) {
                    //有检验，那么判断是否所有检验已经上传成功
                    MedicalChecking queryHasUploadMedicalChecking = new MedicalChecking();
                    queryHasUploadMedicalChecking.setMedicalPatientId(medicalPatient.getId());
                    queryHasUploadMedicalChecking.setUploadFlag(new Short("1"));
                    Long hasUploadMedicalCheckingNum = medicalCheckingDao.selectCount(queryHasUploadMedicalChecking);
                    if (medicalCheckingCheckingSet.size() != hasUploadMedicalCheckingNum) {
                        continue;
                    }

                    //只有检验列表才会有检验明细,所以检验列表通过那么检验明细肯定是下载完成了
                    MedicalCheckingDetail queryHasUploadMedicalCheckingDetail = new MedicalCheckingDetail();
                    queryHasUploadMedicalCheckingDetail.setMedicalPatientId(medicalPatient.getId());
                    queryHasUploadMedicalCheckingDetail.setUploadFlag(new Short("1"));
                    Long hasUploadMedicalCheckingDetailNum = medicalCheckingDetailDao.selectCount(queryHasUploadMedicalCheckingDetail);

                    MedicalCheckingDetail queryMedicalCheckingDetail = new MedicalCheckingDetail();
                    queryMedicalCheckingDetail.setMedicalPatientId(medicalPatient.getId());
                    medicalCheckingDetailNum = medicalCheckingDetailDao.selectCount(queryMedicalCheckingDetail);

                    if ( !medicalCheckingDetailNum.equals(hasUploadMedicalCheckingDetailNum)) {
                        continue;
                    }
                }

                //检查
                if (CollectionUtils.isNotEmpty(medicalExaminationSet)) {
                    //有检查，然后判断是否已经上传完了
                    MedicalExamination queryHasUploadMedicalExamination = new MedicalExamination();
                    queryHasUploadMedicalExamination.setMedicalPatientId(medicalPatient.getId());
                    queryHasUploadMedicalExamination.setUploadFlag(new Short("1"));
                    Long hasUploadMedicalExaminationNum = medicalExaminationDao.selectCount(queryHasUploadMedicalExamination);
                    //没有上传完那么本次完结状态计算结束
                    if (hasUploadMedicalExaminationNum != medicalExaminationSet.size()) {
                        continue;
                    }
                }
                //手术记录
                if (CollectionUtils.isNotEmpty(operationRecordSet)) {
                    //有手术记录，然后判断是否所有的手术记录已经上传成功
                    MedicalOperationRecord queryHasUploadMedicalOperationRecord = new MedicalOperationRecord();
                    queryHasUploadMedicalOperationRecord.setMedicalPatientId(medicalPatient.getId());
                    queryHasUploadMedicalOperationRecord.setUploadFlag(new Short("1"));
                    Long hasUploadMedicalOperationRecordNum = medicalOperationRecordDao.selectCount(queryHasUploadMedicalOperationRecord);

                    if (hasUploadMedicalOperationRecordNum != operationRecordSet.size()) {
                        continue;
                    }
                }

                //总的医疗数据加起来
                Long totalRecordNum = hasUploadMedicalOutpatientFeeNum + hasUploadMedicalOutpatientFeeDetailNum + medicalCheckingCheckingSet.size()
                        + medicalCheckingDetailNum + medicalExaminationSet.size() + operationRecordSet.size() + 1;
                try {
                    String encryptData = Util.encryptMedicalOutlineData(medicalPatient, Integer.valueOf(totalRecordNum.toString()), Constant.ENCRYPT_KEY);
                    SbRequest sbRequest = new SbRequest();
                    sbRequest.setSceneCode(Constant.MEDICAL_OUTLINE_DATA);
                    sbRequest.setEncryptData(encryptData);
                    AlipayCommerceDataSendResponse response = Util.executeUploadMessage(sbRequest);
                    logger.info("mzFeeId={},门诊就诊数据概要支付宝返回参数response={}", new Object[]{medicalPatient.getMzFeeId(),JsonUtils.toJsonString(response)});
                    if (response.isSuccess()) {
                        logger.info("mzFeeId={},门诊就诊数据概要上传成功",medicalPatient.getMzFeeId());
                        medicalPatient.setAllDataUploadCompletedFlag(new Short("1"));
                        medicalPatientDao.update(medicalPatient);
                    }
                } catch (Exception e) {
                    logger.error("门诊就诊数据概要上传系统异常", e);
                }
            }
        }
    }

    public void uploadOutlineInhospitalMessage() {
        logger.info("住院就诊数据概要上传开始");
        MedicalPatient queryMedicalPatient = new MedicalPatient();
        queryMedicalPatient.setOrgCode(Constant.HOSPITAL_CODE);
        queryMedicalPatient.setAllDataUploadCompletedFlag(new Short("0"));
        queryMedicalPatient.setBusinessType(new Short("2"));
        queryMedicalPatient.setAllExaminationUpLoadFlag(new Short("1"));
        queryMedicalPatient.setAllCheckingUpLoadFlag(new Short("1"));
        queryMedicalPatient.setAllOperationUpLoadFlag(new Short("1"));
        List<MedicalPatient> medicalPatientList = medicalPatientDao.select(queryMedicalPatient);

        if (CollectionUtils.isNotEmpty(medicalPatientList)) {
            for (MedicalPatient medicalPatient : medicalPatientList) {
                logger.info("inPatientId={},住院就诊数据概要待上传就诊人信息medicalPatient={}", new Object[]{medicalPatient.getInpatientId(),JsonUtils.toJsonString(medicalPatient)});
                //判断出入院诊断是否已经上传完毕
                MedicalInhospitalDiagnosis queryMedicalInhospitalDiagnosis = new MedicalInhospitalDiagnosis();
                queryMedicalInhospitalDiagnosis.setMedicalPatientId(medicalPatient.getId());
                queryMedicalInhospitalDiagnosis.setUploadFlag(new Short("1"));
                Long hasUploadMedicalInhospitalDiagnosis = medicalInhospitalDiagnosisDao.selectCount(queryMedicalInhospitalDiagnosis);
                if(hasUploadMedicalInhospitalDiagnosis !=2){
                    continue;
                }
                //已经上传的费用信息
                MedicalInhospitalFee queryHasUploadMedicalInhospitalFee = new MedicalInhospitalFee();
                queryHasUploadMedicalInhospitalFee.setMedicalPatientId(medicalPatient.getId());
                queryHasUploadMedicalInhospitalFee.setUploadFlag(new Short("1"));
                Long hasUploadMedicalInhospitalFeeNum = medicalInhospitalFeeDao.selectCount(queryHasUploadMedicalInhospitalFee);
                //费用列表条数
                MedicalInhospitalFee queryMedicalInhospitalFee = new MedicalInhospitalFee();
                queryMedicalInhospitalFee.setMedicalPatientId(medicalPatient.getId());
                Long medicalInhospitalFeeNum = medicalInhospitalFeeDao.selectCount(queryMedicalInhospitalFee);
                if (hasUploadMedicalInhospitalFeeNum != medicalInhospitalFeeNum) {
                    continue;
                }

                //已上传费用明细条数
                MedicalInhospitalFeeDetail queryHasUploadMedicalInhospitalFeeDetail = new MedicalInhospitalFeeDetail();
                queryHasUploadMedicalInhospitalFeeDetail.setMedicalPatientId(medicalPatient.getId());
                queryHasUploadMedicalInhospitalFeeDetail.setUploadFlag(new Short("1"));
                Long hasUploadMedicalInhospitalFeeDetailNum = medicalInhospitalFeeDetailDao.selectCount(queryHasUploadMedicalInhospitalFeeDetail);

                MedicalInhospitalFeeDetail queryMedicalInhospitalFeeDetail = new MedicalInhospitalFeeDetail();
                queryMedicalInhospitalFeeDetail.setMedicalPatientId(medicalPatient.getId());
                List<MedicalInhospitalFeeDetail> medicalInhospitalFeeDetailNum = medicalInhospitalFeeDetailDao.select(queryMedicalInhospitalFeeDetail);

                if (CollectionUtils.isEmpty(medicalInhospitalFeeDetailNum) ||hasUploadMedicalInhospitalFeeDetailNum != medicalInhospitalFeeDetailNum.size() ){
                    continue;
                }
                //住院的报告总条数
                //计算本次住院流程总的报告条数
                Set<String> medicalCheckingCheckingSet = new HashSet<String>();
                Set<String> medicalExaminationSet = new HashSet<String>();
                Set<String> operationRecordSet = new HashSet<String>();
                MedicalInhospitalReportids queryMedicalInhospitalReportids = new MedicalInhospitalReportids();
                queryMedicalInhospitalReportids.setMedicalPatientId(medicalPatient.getId());
                List <MedicalInhospitalReportids> medicalInhospitalReportidsList = medicalInhospitalReportidsDao.select(queryMedicalInhospitalReportids);
                if(CollectionUtils.isNotEmpty(medicalInhospitalReportidsList)){
                    for (MedicalInhospitalReportids medicalInhospitalReportids :medicalInhospitalReportidsList){
                        if (StringUtils.isNotEmpty(medicalInhospitalReportids.getReportId()) && medicalInhospitalReportids.getReportType() == 1){
                            medicalExaminationSet.add(medicalInhospitalReportids.getReportId());
                        }

                        if (StringUtils.isNotEmpty(medicalInhospitalReportids.getReportId()) && medicalInhospitalReportids.getReportType() == 2){
                            medicalCheckingCheckingSet.add(medicalInhospitalReportids.getReportId());
                        }

                        if (StringUtils.isNotEmpty(medicalInhospitalReportids.getReportId()) && medicalInhospitalReportids.getReportType() == 3){
                            operationRecordSet.add(medicalInhospitalReportids.getReportId());
                        }
                    }
                }

                Long medicalCheckingDetailNum = 0L;
                if (CollectionUtils.isNotEmpty(medicalCheckingCheckingSet)) {
                    //有检验，那么判断是否所有检验已经上传成功
                    MedicalChecking queryHasUploadMedicalChecking = new MedicalChecking();
                    queryHasUploadMedicalChecking.setMedicalPatientId(medicalPatient.getId());
                    queryHasUploadMedicalChecking.setUploadFlag(new Short("1"));
                    Long hasUploadMedicalCheckingNum = medicalCheckingDao.selectCount(queryHasUploadMedicalChecking);
                    if (medicalCheckingCheckingSet.size() != hasUploadMedicalCheckingNum) {
                        continue;
                    }

                    //只有检验列表才会有检验明细,所以检验列表通过那么检验明细肯定是下载完成了
                    MedicalCheckingDetail queryHasUploadMedicalCheckingDetail = new MedicalCheckingDetail();
                    queryHasUploadMedicalCheckingDetail.setMedicalPatientId(medicalPatient.getId());
                    queryHasUploadMedicalCheckingDetail.setUploadFlag(new Short("1"));
                    Long hasUploadMedicalCheckingDetailNum = medicalCheckingDetailDao.selectCount(queryHasUploadMedicalCheckingDetail);

                    MedicalCheckingDetail queryMedicalCheckingDetail = new MedicalCheckingDetail();
                    queryMedicalCheckingDetail.setMedicalPatientId(medicalPatient.getId());
                    medicalCheckingDetailNum = medicalCheckingDetailDao.selectCount(queryMedicalCheckingDetail);

                    if (!medicalCheckingDetailNum.equals(hasUploadMedicalCheckingDetailNum)) {
                        continue;
                    }
                }

                //检查
                if (CollectionUtils.isNotEmpty(medicalExaminationSet)) {
                    //有检查，然后判断是否已经上传完了
                    MedicalExamination queryHasUploadMedicalExamination = new MedicalExamination();
                    queryHasUploadMedicalExamination.setMedicalPatientId(medicalPatient.getId());
                    queryHasUploadMedicalExamination.setUploadFlag(new Short("1"));
                    Long hasUploadMedicalExaminationNum = medicalExaminationDao.selectCount(queryHasUploadMedicalExamination);
                    //没有上传完那么本次完结状态计算结束
                    if (hasUploadMedicalExaminationNum != medicalExaminationSet.size()) {
                        continue;
                    }
                }
                //手术记录
                if (CollectionUtils.isNotEmpty(operationRecordSet)) {
                    //有手术记录，然后判断是否所有的手术记录已经上传成功
                    MedicalOperationRecord queryHasUploadMedicalOperationRecord = new MedicalOperationRecord();
                    queryHasUploadMedicalOperationRecord.setMedicalPatientId(medicalPatient.getId());
                    queryHasUploadMedicalOperationRecord.setUploadFlag(new Short("1"));
                    Long hasUploadMedicalOperationRecordNum = medicalOperationRecordDao.selectCount(queryHasUploadMedicalOperationRecord);

                    if (hasUploadMedicalOperationRecordNum != operationRecordSet.size()) {
                        continue;
                    }
                }

                //总条数
                Long totalRecordNum = 2 +medicalInhospitalFeeNum + medicalInhospitalFeeDetailNum.size() + medicalCheckingCheckingSet.size()
                        + medicalCheckingDetailNum + medicalExaminationSet.size() + operationRecordSet.size();
                try {
                    String encryptData = Util.encryptMedicalOutlineInhospitalData(medicalPatient, Integer.valueOf(totalRecordNum.toString()), Constant.ENCRYPT_KEY);
                    SbRequest sbRequest = new SbRequest();
                    sbRequest.setSceneCode(Constant.MEDICAL_OUTLINE_DATA);
                    sbRequest.setEncryptData(encryptData);
                    AlipayCommerceDataSendResponse response = Util.executeUploadMessage(sbRequest);
                    logger.info("inPatientId={},住院就诊数据概要支付宝返回参数response={}", new Object[]{medicalPatient.getInpatientId(),JsonUtils.toJsonString(response)});
                    if (response.isSuccess()) {
                        logger.info("inPatientId={},住院就诊数据概要上送支付宝成功",medicalPatient.getInpatientId());
                        medicalPatient.setAllDataUploadCompletedFlag(new Short("1"));
                        medicalPatientDao.update(medicalPatient);
                    }
                } catch (Exception e) {
                    logger.error("住院就诊数据概要上送支付宝失败", e);
                }
            }
        }
    }
}
